from fastapi import APIRouter, Query, Path
from fastapiApp.controllers.order_control import order_controller
from fastapiApp.schemas.base_scheams import Fail, Success, SuccessExtra
from fastapiApp.schemas.order_scheams import OrderCreate, OrderUpdate
from fastapiApp.models.enums import OrderStatus

router = APIRouter()


@router.get("/page", summary="获取分页数据")
async def get_order_page(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=1000, description="每页数量")
):
    """获取订单分页列表"""
    total, data = await order_controller.list(page=page, page_size=page_size)
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)


@router.post("/create", summary="创建订单")
async def create_order(obj_in: OrderCreate):
    """创建订单"""
    await order_controller.is_exist(obj_in=obj_in)
    # 转换输入数据为字典
    data = obj_in.model_dump()
    
    order_data = {
        "car_index": data["car_index"],
        "order_name": data["order_name"],
        "user_id": data["user_id"],
        "type": data["type"],
        "status": data["status"],
        "car_index": data["car_index"],
        "priority": data["priority"],
        "order_station_from_id": data.get("order_station_from"),
        "order_station_to_id": data.get("order_station_to"),
    }

    await order_controller.model.create(**order_data)
    return Success(msg="Created Successfully")


@router.patch("/orders/{id}", summary="修改订单状态")
async def patch_order(id: int, status: OrderStatus):
    """修改订单状态"""
    order = await order_controller.model.get_or_none(id=id)
    if not order:
        return Fail(msg="订单不存在")
    else:
        order.status = status
        await order.save()
        return Success(msg="update success")


@router.put("/orders/{id}", summary="更新订单")
async def update_order(obj_in: OrderUpdate):
    """更新订单"""
    await order_controller.update(obj_in)
    return Success(msg=f"Update Successfully By ID = {obj_in.id}")

@router.delete("/delete/{id}", summary="删除订单")
async def delete_order(id: int = Path(..., ge=0, description="ID")):
    """
    删除订单
    """
    obj = await order_controller.model.get_or_none(id=id)
    if obj:
        await obj.delete()
        return Success(msg=f"Deleted Success By ID = {id}")
    else:
        return Fail(msg=f"ID {id} 不存在")



